package com.dranie.action;

import com.dranie.entity.Category;
import com.dranie.entity.Goods;
import com.dranie.entity.User;
import com.dranie.interceptor.GoodsInterceptor;
import com.dranie.validator.GoodsValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

import java.util.Arrays;
import java.util.List;

/**
 * goodsController
 * 注意：在实际项目中业务与sql需要写在Model中，此demo仅为示意,故将sql写在了Controller中
 */
@Before(GoodsInterceptor.class)
public class GoodsController extends Controller {
    public void index() {
        Page<Goods> goodsPage = Goods.dao.paginate(getParaToInt(0, 1), 10, "select g.id,g.name,g.categoryId,g.price,g.img,g.memo,c.name cname,g.imgs", "from goods g left join category c on c.id=g.categoryId order by g.id asc");

        for (Goods g : goodsPage.getList()) {
            if (g.get("imgs") != null) {
                String[] imgs = g.get("imgs").toString().split("\\|\\|");
                g.put("imgList", imgs);
            }
        }

        setAttr("goodsPage", goodsPage);
        render("list.html");
    }

    public void add() {
        List<Category> categorys = Category.dao.find("select * from category where parent is null");
        setAttr("categorys", categorys);
    }

    @Before(GoodsValidator.class)
    public void save() {
        Goods goods = getModel(Goods.class);
        goods.save();
        redirect("/admin/goods");
    }

    public void edit() {
        List<Category> categorys = Category.dao.find("select * from category where parent is null");
        setAttr("categorys", categorys);
        Goods g = Goods.dao.findById(getParaToInt());
        if (g.get("imgs") != null) {
            String imgsStr = g.get("imgs").toString().replaceFirst("\\|\\|","");
            String[] imgs = imgsStr.split("\\|\\|");
            g.put("imgList", Arrays.asList(imgs));
        }
        setAttr("goods", g);
    }

    @Before(GoodsValidator.class)
    public void update() {
        Goods goods = getModel(Goods.class);
        goods.update();
        redirect("/admin/goods");
    }

    public void delete() {
        Goods.dao.deleteById(getParaToInt());
        redirect("/admin/goods");
    }
}


